package com.tedu.sp11.fallback;

import com.tedu.sp01.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ItemFB implements FallbackProvider {
    //返回一个 service id,针对指定的服务进行降级处理
    //返回*或者null值，对所有服务都应用这个降级类
    @Override
    public String getRoute() {
        return "item-service";//只针对商品服务类降级
    }
    //降级响应，返回一个 封装响应数据的response对象，
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        //对响应数据进行配置
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                //响应数据的封装对象 200,"ok"
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();//返回一个协议状态码：200
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();//状态文本："OK"
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                //JsonResult{code:401,msg:调用商品服务失败 ，data:null}
                String json= JsonResult.err().msg("调用商品服务失败").toString();
                return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpHeaders getHeaders() {
                 HttpHeaders h=new HttpHeaders();
                 h.add("content-Type","application/json;charset=UTF-8");
                 return h;
            }
        };
    }
}
